package com.xyy.saas.payment.service.excel.impl;

import com.xyy.saas.payment.cores.enums.TransactionTypeEnum;
import com.xyy.saas.payment.dao.mapper.PrePayOrderMapper;
import com.xyy.saas.payment.dao.mapper.RefundOrderMapper;
import com.xyy.saas.payment.dao.model.PayResultOrder;
import com.xyy.saas.payment.dao.model.PrePayOrder;
import com.xyy.saas.payment.dao.model.RefundOrder;
import com.xyy.saas.payment.exception.PaymentException;
import com.xyy.saas.payment.manage.cores.vo.ResultVO;
import com.xyy.saas.payment.service.PayResultOrderService;
import com.xyy.saas.payment.service.excel.AbstractAnalysisFile;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AnalysisPayRecordExcelService extends AbstractAnalysisFile {

    @Autowired
    private PayResultOrderService payResultOrderService;

    @Resource
    private PrePayOrderMapper prePayOrderMapper;

    @Resource
    private RefundOrderMapper refundOrderMapper;

    @Override
    protected ResultVO checkFile(MultipartFile file) {
        //检查文件是否为空
        boolean empty = file.isEmpty();
        if(empty || file == null){
            return ResultVO.createError("文件错误!");
        }
        //检查文件是否是excel类型文件
        String filename = file.getOriginalFilename();
        if(!filename.endsWith("xls") && !filename.endsWith("xlsx")){
            return ResultVO.createError("文件格式错误!");
        }
        return ResultVO.createSuccess();
    }

    @Override
    protected Map<String, ArrayList<String[]>> processData(Map<String, ArrayList<String[]>> hashMap) {
        Map<String, ArrayList<String[]>> result = new HashMap<>();
        for (String tradeType : hashMap.keySet()) {
            if(TransactionTypeEnum.PAY.getCode().equals(tradeType)) {
                ArrayList<String[]> rowResult = new ArrayList<>();
                for (int row = 0 ; row < hashMap.get(tradeType).size() ; row++) {
                    if(StringUtils.isBlank(hashMap.get(tradeType).get(row)[0])) {
                        continue;
                    }
                    List<PayResultOrder> payResultOrders = payResultOrderService.selectListByPayNo(hashMap.get(tradeType).get(row)[0]);
                    if(null == payResultOrders) {
                        continue;
                    }
                    PrePayOrder prepayOrder = prePayOrderMapper.getPrePayOrderByPayNo(hashMap.get(tradeType).get(row)[0]);
                    for (PayResultOrder payResultOrder : payResultOrders) {
                        String[] s = new String[2];
                        s[0] = payResultOrder.getPayNo();
                        s[1] = prepayOrder.getBusinessOrderNo();
                        rowResult.add(s);
                    }
                }
                result.put(tradeType, rowResult);
            }
            if(TransactionTypeEnum.REFUND.getCode().equals(tradeType)) {
                ArrayList<String[]> rowResult = new ArrayList<>();
                for (int row = 0 ; row < hashMap.get(tradeType).size() ; row++) {
                    if(StringUtils.isBlank(hashMap.get(tradeType).get(row)[0])) {
                        continue;
                    }
                    RefundOrder refundOrder = refundOrderMapper.selectByRefundNo(hashMap.get(tradeType).get(row)[0]);
                    if(null == refundOrder) {
                        continue;
                    }
                    String[] s = new String[2];
                    s[0] = refundOrder.getRefundNo();
                    s[1] = refundOrder.getBusinessRefundNo();
                    rowResult.add(s);
                }
                result.put(tradeType, rowResult);
            }
        }
        return result;
    }

    @Override
    protected ResultVO checkData(Map<String, ArrayList<String[]>> hashMap) {
        return ResultVO.createSuccess();
    }

    @Override
    protected Map<String, ArrayList<String[]>> analysisFile(MultipartFile file) throws PaymentException {
        try {
            Map<String, ArrayList<String[]>> data = new HashMap<>();
            //获取workbook对象
            Workbook workbook = null;
            String filename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            //根据后缀名是否excel文件
            if(filename.endsWith("xls")){
                //2003
                workbook = new HSSFWorkbook(inputStream);
            }else if(filename.endsWith("xlsx")){
                //2007
                workbook = new XSSFWorkbook(inputStream);
            }

            try {
                if(workbook != null){
                    //循环sheet,现在是单sheet
                    for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
                        //创建对象，把每一行作为一个String数组，所以数组存到集合中
                        ArrayList<String[]> arrayList = new ArrayList<>();
                        //获取第一个sheet
                        Sheet sheet = workbook.getSheetAt(sheetNum);
                        if(sheet == null){
                            data.put("文件sheet为空!",arrayList);
                            return data;
                        }
                        //获取当前sheet开始行和结束行
                        int firstRowNum = sheet.getFirstRowNum();
                        int lastRowNum = sheet.getLastRowNum();
                        //循环开始，除了前两行
                        for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
                            //获取当前行
                            Row row = sheet.getRow(rowNum);
                            //获取当前行的开始列和结束列
                            short firstCellNum = row.getFirstCellNum();
                            short lastCellNum = row.getLastCellNum();

                            //获取总行数
                            int lastCellNum2 = row.getPhysicalNumberOfCells();
                            String[] strings = new String[lastCellNum2];
                            //循环当前行
                            for(int cellNum = firstCellNum;cellNum < lastCellNum;cellNum++){
                                Cell cell = row.getCell(cellNum);
                                if( cell == null || "".equals(cell) || cell.getCellType()== Cell.CELL_TYPE_BLANK ){
                                    strings[cellNum] = "";
                                    continue;
                                }
                                String  cellValue = "";
                                cellValue = getCellValue(cell);
                                strings[cellNum] = cellValue;
                            }
                            arrayList.add(strings);
                        }
                        data.put(sheet.getSheetName(),arrayList);
                    }
                }
            } catch (Exception e) {

            }finally {
                inputStream.close();
            }
            return data;
        } catch (Exception e) {
            throw new PaymentException(e.getMessage());
        }
    }


    @Override
    protected void processExcel(Map<String, ArrayList<String[]>> result, HttpServletResponse response) throws PaymentException {
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            for (String sheetName : result.keySet()) {
                HSSFSheet sheet = workbook.createSheet(sheetName);
                //添加表头
                String titleRow[] = {"支付单号", "业务单号"};
                HSSFRow row = sheet.createRow(0);    //创建第一行
                for(short i = 0;i < titleRow.length;i++){
                    HSSFCell cell = row.createCell(i);
                    cell.setCellValue(titleRow[i]);
                }
                for (int index=1; index<result.get(sheetName).size()+1;index++) {
                    String exampleRow[] = result.get(sheetName).get(index-1);
                    HSSFRow row_2 = sheet.createRow(index);    //创建第一行
                    for(short i = 0;i < exampleRow.length;i++){
                        HSSFCell cell = row_2.createCell(i);
                        cell.setCellValue(exampleRow[i]);
                    }
                }
            }

            OutputStream output=response.getOutputStream();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=2020_contract_search_number_0001.xls");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            workbook.write(output);
            output.close();
        } catch (Exception e) {
            throw new PaymentException(e.getMessage());
        }
    }

    //把每一个cell转换为string
    private String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //把数字转换成string，防止12.0这种情况
        if(cell.getCellType() == cell.CELL_TYPE_NUMERIC){
            cell.setCellType(cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //数字0
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串1
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                //cellValue = String.valueOf(cell.getCellFormula());
                try {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                } catch (IllegalStateException e) {
                    cellValue = String.valueOf(cell.getRichStringCellValue());
                }
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
}
